/**
 * datagrid based on dataTable
 *
 * Dependencies:
 *     dataTable
 *
 */
(function ($) {
    var tableOptions; // main option
    var dataTable; // datatable object
    var table; // actual table jquery object
    var tableContainer; // actual table container object
    var tableWrapper; // actual table wrapper jquery object
    var tableInitialized = false;
    var ajaxParams = {}; // set filter mode
    var the;

    var isSelect = {
        style: 'os',
    };

    var isMultipleSelect = {
        style: 'multi',
    };


    /**
     * 第一列自带checkbox
     */
    var columnCheckDefs = [
        {
            orderable: false,
            className: 'checkboxes',
            targets: 0
        },

    ];
    /**
     * 第一列不带checkbox
     */
    var columnDefs = [
        {
            "render": function (data, type, row) {
                if (data == undefined) {
                    return "";
                } else {
                    return data;
                }
            },
            'orderable': false,
            'targets': '_all'
        }
    ];


    function init(container, options, dataTableId) {
        if (!$().dataTable) {
            return;
        }

        if (options.dataTable.isCheckbox) {
            options.dataTable.columnDefs = columnCheckDefs;
            options.dataTable.select = isMultipleSelect;
        } else {
            options.dataTable.columnDefs = columnDefs;
        }


        // initialize a datatable
        var dataTable = $('#' + dataTableId + '').DataTable(options.dataTable);
        $('#' + dataTableId + '').data("gridObj", dataTable);
        // dataTable = table.DataTable(options.dataTable);
        return dataTable;
    }

    $.fn.datagrid = function (options, param) {
        if (this[0] != undefined) {
            setCheckBox(this[0].id);
        }
        if (typeof options == 'string') {
            return $.fn.datagrid.methods[options](this, param);
        }

        options = options || {};

        var state = $.data(this, 'datagrid');
        var opts;
        var tableId;
        if (state) {
            opts = $.extend(state.options, options);
            state.options = opts;
        } else {
            // 如果使用的是静态数据 则用静态数据渲染 否则用 ajax
            if (options.dataTable.data) {
                opts = $.extend(true, {}, $.fn.datagrid.staticDataOption, options);
            } else {
                opts = $.extend(true, {}, $.fn.datagrid.defaults, options);
                /**
                 * 省略配置 ajax{} 对象
                 */
                if (opts.dataTable.url) {
                    opts.dataTable.ajax.url = opts.dataTable.url;
                }

            }
            if (this[0] != undefined) {
                tableId = this[0].id;
            } else {
                tableId = this.selector.substring(1);
            }
            $('#' + tableId + '').data("datatableOptions", opts.dataTable);

        }

        return init(this, opts, tableId);
    };


    //     //从 页面上获取 datagrid 的 Jquery对象
    //     var state = $.data(this, 'datagrid');
    //     var opts;
    //
    //     // 如果 表格已经不是第一次加载
    //     if(state){
    //         opts= $.extend(state.options, options);
    //         state.options = opts;
    //     }else {
    //         opts = $.extend(true,$.fn.datagrid.defaults,options);
    //     }
    //
    //
    //     $.data(this, 'datagrid', {
    //         options: opts,
    //         selectedRows: [],
    //         checkedRows: [],
    //         data: {total:0,rows:[]},
    //         originalRows: [],
    //         updatedRows: [],
    //         insertedRows: [],
    //         deletedRows: []
    //     });
    //     debugger;
    //     // init(this, options);
    //     return init(this, opts);
    // };


    $.fn.datagrid.methods = {
        options: function (jq) {
            return $.data(jq[0], 'datagrid').options;
        },
        panels: function (jq) {
            return $.data(jq[0], 'datagrid').panels;
        },
        resize: function (jq, param) {
            return jq.each(function () {
                setSize(this, param);
            });
        },
        getSelections: function (jq) {

            var table = $("#" + jq[0].id + "").data("gridObj");
            var data = table.rows({selected: true}).data();
            var rows = new Array();

            for (var i = 0; i < data.length; i++) {
                rows.push(data[i]);
            }
            return rows;
        },
        getSelected: function (jq) {
            var state = $.data(jq, 'datagrid');
            var state1 = $.data(jq[0], 'datagrid');

        },
        getPanel: function (jq, which) {
            return getPanel(jq[0], which);
        },
        getPanelIndex: function (jq, panel) {
            return getPanelIndex(jq[0], panel);
        },
        select: function (jq, which) {
            return jq.each(function () {
                select(this, which);
            });
        },
        getRows: function (jq) {
            var table = $("#" + jq[0].id + "").data("gridObj");
            var data = table.rows().data();
            var rows = new Array();
            for (var i = 0; i < data.length; i++) {
                rows.push(data[i]);
            }
            return rows;
        },
        selectAll: function (jq) {
            var table = $("#" + jq[0].id + "").data("gridObj");
            table.rows().select();
        },
        unselectAll: function (jq) {
            var table = $("#" + jq[0].id + "").data("gridObj");
            table.rows().deselect();
        },
        unselect: function (jq, which) {
            var table = $("#" + jq[0].id + "").data("gridObj");
            table.rows({selected: true}).data();
        },
        add: function (jq, options) {
            return jq.each(function () {
                add(this, options);
            });
        },
        remove: function (jq, which) {
            return jq.each(function () {
                remove(this, which);
            });
        },
        reload: function (jq, which) {
            var tableId = '';
            if (jq[0] != undefined) {
                tableId = jq[0].id;
            } else {
                tableId = jq.selector.substring(1);
            }
            if (!which) {
                which = 'searchForm';
            }
            var params = $("#" + which).serializeObject();
            var table = $("#" + tableId + "").data("gridObj");
            table.settings()[0].ajax.data = params;
            table.ajax.reload();
        }
    };

    $.fn.datagrid.parseOptions = function (target) {
        var t = $(target);
        return $.extend({}, $.parser.parseOptions(target, [
            'width', 'height',
            {fit: 'boolean', border: 'boolean', animate: 'boolean', multiple: 'boolean', selected: 'number'}
        ]));
    };


    /****
     * 静态 JavaScript数据源渲染 渲染datatable的对象
     */
    $.fn.datagrid.staticDataOption = {
        dataTable: {
            "dom": "rt<'row'<'col-md-4 col-sm-12'l><'col-md-4 col-sm-12'i><'col-md-4 col-sm-12 pull-right'p>>",
            "pageLength": 10, // default records per page
            "searching": true,
            "pagingType": "bootstrap_extended", // pagination type(bootstrap, bootstrap_full_number or bootstrap_extended)
            "autoWidth": false, // disable fixed width and enable fluid table
            "serverSide": false, // 开启/关闭  服务器 ajax分页
        }

    };


    /****
     * 覆盖调datatable 弹出框显示错误信息
     * @param s
     * @param h
     * @param m
     */
    $.fn.dataTable.ext.errMode = function (s, h, m) {
        console.log("datatable 警告信息:", s, h, m);
    }


    $.fn.datagrid.defaults = {
        dataTable: {
            "dom": "rt<'row'<'col-md-4 col-sm-12'l><'col-md-4 col-sm-12'i><'col-md-4 col-sm-12 pull-right'p>>", // datatable layout
            "pageLength": 10, // default records per page
            buttons: [
                {extend: 'print', className: 'btn dark btn-outline'},
                {extend: 'copy', className: 'btn red btn-outline'},
                {extend: 'pdf', className: 'btn green btn-outline'},
                {extend: 'excel', className: 'btn yellow btn-ofutline '},
                {extend: 'csv', className: 'btn purple btn-outline '},
                {extend: 'colvis', className: 'btn dark btn-outline', text: 'Columns'}
            ],
            "lengthMenu": [
                [10, 20, 50, 150, -1],
                [10, 20, 50, 150, "All"] // change per page values here
            ],
            "orderCellsTop": true,

            // 定义表格的默认属性：
            // render 表格渲染事件
            // targets 表示列的标识  从0开始  -1:代表最后一列  _all:代表所有列
            "columnDefs": [
                { // define columns sorting options(by default all columns are sortable extept the first checkbox column)
                    "render": function (data, type, row) {
                        return "<input type='checkbox' name='onDutyToId'  value='" + data + "'>";
                    },
                    'orderable': false,
                    'targets': [0]
                }

            ],
            //"lengthChange": false,
            "searching": true,
            "ordering": true,
            "pagingType": "bootstrap_extended", // pagination type(bootstrap, bootstrap_full_number or bootstrap_extended)
            "autoWidth": false, // disable fixed width and enable fluid table
            "processing": true, // enable/disable display message box on record load
            "serverSide": true, // enable/disable server side ajax loading
            "ajax": { // define ajax settings
                "url": "", // ajax URL
                "type": "POST", // request type
                "timeout": 20000,
                "data": function (data) { // add request parameters before submit
                    var pageParam = {};
                    pageParam.draw = data.draw;
                    pageParam.length = data.length;
                    pageParam.start = data.start;
                    if (data.order != undefined) {
                        for (var i = 0; i < data.order.length; i++) {
                            if (pageParam.sort == undefined) {
                                pageParam.sort = data.columns[data.order[i].column].data + " " + data.order[i].dir
                            } else {
                                pageParam.sort = data.columns[data.order[i].column].data + " " + data.order[i].dir + ", " + pageParam.sort;
                            }
                        }
                    }
                    return pageParam;
                },
                "dataSrc": function (res) { // Manipulate the data returned from the server
                    if (res.customActionMessage) {
                        App.alert({
                            type: (res.customActionStatus == 'OK' ? 'success' : 'danger'),
                            icon: (res.customActionStatus == 'OK' ? 'check' : 'warning'),
                            message: res.customActionMessage,
                            container: tableWrapper,
                            place: 'prepend'
                        });
                    }

                    if (res.customActionStatus) {
                        if (tableOptions.resetGroupActionInputOnSuccess) {
                            $('.table-group-action-input', tableWrapper).val("");
                        }
                    }

                    if ($('.group-checkable', table).size() === 1) {
                        $('.group-checkable', table).attr("checked", false);
                    }
                    //
                    // if (tableOptions.onSuccess) {
                    //     tableOptions.onSuccess.call(undefined, the, res);
                    // }

                    App.unblockUI(tableContainer);

                    return res.rows;
                },
                "error": function () { // handle general connection errors
                    // if (tableOptions.onError) {
                    //     tableOptions.onError.call(undefined, the);
                    // }
                    //
                    // App.alert({
                    //     type: 'danger',
                    //     icon: 'warning',
                    //     message: tableOptions.dataTable.language.metronicAjaxRequestGeneralError,
                    //     container: tableWrapper,
                    //     place: 'prepend'
                    // });
                    //
                    // App.unblockUI(tableContainer);
                }
            },

            "drawCallback": function (oSettings) { // run some code on table redraw

            },
            ajaxParams: {}


        }


    };


    /**
     * 为每个全选checkbox 绑定全选事件
     * @param Id
     */
    function setCheckBox(Id) {
        $("#" + Id + " td").each(
            function () {
                if ($(this).attr("class") == "box") {
                    $(this).click(function () {
                        if ($(this).parent().hasClass("selected")) {
                            $(this).parent().removeClass("selected");
                            dataTable.rows().deselect();
                        } else {
                            $(this).parent().addClass("selected");
                            dataTable.rows().select();
                        }
                    });
                }

            }
        );
    }

    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    }


})(jQuery);
